package com.xishu.service;

import com.xishu.entity.area.Area;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Optional;

public class AreaService {
    private static AreaService instance = new AreaService();
    private CommonService commonService = CommonService.getInstance();

    private AreaService() {
    }

    public static AreaService getInstance() {
        return instance;
    }

    /**
     * 将名称转化成ID列表
     *
     * @param areaName
     * @return
     */
    public String areaNameToInt(String areaName) {
        String[] nameList = areaName.split("\\s+");
        ArrayList<Long> idList = new ArrayList<>();

        for (String name : nameList) {
            Optional<Area> nameOptional = searchName(name);
            if (nameOptional.isPresent()) {
                idList.add(nameOptional.get().getId());
                continue;
            }

            nameOptional = searchName_zh(name);
            if (nameOptional.isPresent()) {
                idList.add(nameOptional.get().getId());
                continue;
            }

            nameOptional = searchName_en(name);
            if (nameOptional.isPresent()) {
                idList.add(nameOptional.get().getId());
                continue;
            }
        }

        return StringUtils.join(idList, ",");
    }

    public Optional<Area> searchName(String name) {
        Area area = new Area();
        area.setName(name);
        return commonService.searchOneOptional(area);
    }

    public Optional<Area> searchName_zh(String name) {
        Area area = new Area();
        area.setName_zh(name);
        return commonService.searchOneOptional(area);
    }

    public Optional<Area> searchName_en(String name) {
        Area area = new Area();
        area.setName_en(name);
        return commonService.searchOneOptional(area);
    }
}
